#include "library.h"

// 借阅图书
void borrowBook() {
    if (currentUser == NULL) {
        printf("请先登录!\n");
        return;
    }

    int bookId;
    printf("\n--- 借阅图书 ---\n");
    printf("请输入要借阅的图书ID: ");
    scanf("%d", &bookId);
    clearInputBuffer();

    // 检查图书状态
    sqlite3_stmt *stmt;
    const char *sql = "SELECT status, borrowerId FROM book WHERE id = ?";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    sqlite3_bind_int(stmt, 1, bookId);
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_ROW) {
        printf("未找到ID为%d的图书!\n", bookId);
        sqlite3_finalize(stmt);
        return;
    }

    Booktatus status = (Booktatus)sqlite3_column_int(stmt, 0);
    int borrowerId = sqlite3_column_int(stmt, 1);
    sqlite3_finalize(stmt);

    if (status == BOOK_AVAILABLE) {
        time_t now = time(NULL);
        time_t returnDate = now + 30 * 24 * 60 * 60; // 30天后应还

        // 更新图书状态
        sql = "UPDATE book SET status = ?, borrowerId = ?, borrowDate = ?, returnDate = ? WHERE id = ?";
        rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
        if (rc != SQLITE_OK) {
            fprintf(stderr, "SQL错误: %s\n", sqlite3_errmsg(db));
            return;
        }

        sqlite3_bind_int(stmt, 1, BOOK_BORROWED);
        sqlite3_bind_int(stmt, 2, currentUser->id);
        sqlite3_bind_int64(stmt, 3, now);
        sqlite3_bind_int64(stmt, 4, returnDate);
        sqlite3_bind_int(stmt, 5, bookId);
        rc = sqlite3_step(stmt);
        sqlite3_finalize(stmt);

        if (rc != SQLITE_DONE) {
            fprintf(stderr, "更新图书状态失败: %s\n", sqlite3_errmsg(db));
            return;
        }

        // 添加借阅记录
        sql = "INSERT INTO record (userId, bookId, borrowDate, returnDate, returned) VALUES (?, ?, ?, ?, 0)";
        rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
        if (rc != SQLITE_OK) {
            fprintf(stderr, "SQL错误: %s\n", sqlite3_errmsg(db));
            return;
        }

        sqlite3_bind_int(stmt, 1, currentUser->id);
        sqlite3_bind_int(stmt, 2, bookId);
        sqlite3_bind_int64(stmt, 3, now);
        sqlite3_bind_int64(stmt, 4, returnDate);
        rc = sqlite3_step(stmt);
        sqlite3_finalize(stmt);

        if (rc != SQLITE_DONE) {
            fprintf(stderr, "添加借阅记录失败: %s\n", sqlite3_errmsg(db));
        } else {
            printf("图书借阅成功! 应还日期: %s", ctime(&returnDate));
        }
    } else if (status == BOOK_BORROWED) {
        printf("该图书已被借出!\n");
    } else {
        printf("该图书已丢失!\n");
    }
}

// 归还图书
void returnBook() {
    if (currentUser == NULL) {
        printf("请先登录!\n");
        return;
    }

    int bookId;
    printf("\n--- 归还图书 ---\n");
    printf("请输入要归还的图书ID: ");
    scanf("%d", &bookId);
    clearInputBuffer();

    // 检查图书是否由当前用户借出
    sqlite3_stmt *stmt;
    const char *sql = "SELECT status, borrowerId FROM book WHERE id = ?";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    sqlite3_bind_int(stmt, 1, bookId);
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_ROW) {
        printf("未找到ID为%d的图书!\n", bookId);
        sqlite3_finalize(stmt);
        return;
    }

    Booktatus status = (Booktatus)sqlite3_column_int(stmt, 0);
    int borrowerId = sqlite3_column_int(stmt, 1);
    sqlite3_finalize(stmt);

    if (status != BOOK_BORROWED || borrowerId != currentUser->id) {
        printf("未找到您借阅的ID为%d的图书!\n", bookId);
        return;
    }

    // 更新图书状态
    sql = "UPDATE book SET status = ?, borrowerId = -1, borrowDate = 0, returnDate = 0 WHERE id = ?";
    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    sqlite3_bind_int(stmt, 1, BOOK_AVAILABLE);
    sqlite3_bind_int(stmt, 2, bookId);
    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);

    if (rc != SQLITE_DONE) {
        fprintf(stderr, "更新图书状态失败: %s\n", sqlite3_errmsg(db));
        return;
    }

    // 更新借阅记录
    sql = "UPDATE record SET returned = 1 WHERE bookId = ? AND userId = ? AND returned = 0";
    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    sqlite3_bind_int(stmt, 1, bookId);
    sqlite3_bind_int(stmt, 2, currentUser->id);
    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);

    if (rc != SQLITE_DONE) {
        fprintf(stderr, "更新借阅记录失败: %s\n", sqlite3_errmsg(db));
    } else {
        printf("图书归还成功!\n");
    }
}

// 查看借阅历史
void viewBorrowHistory() {
    if (currentUser == NULL) {
        printf("请先登录!\n");
        return;
    }

    printf("\n--- 借阅历史 ---\n");
    sqlite3_stmt *stmt;
    const char *sql;

    if (currentUser->power == USER_ROOT) {
        // 管理员查看所有记录
        sql = "SELECT br.id, br.userId, u.username, br.bookId, b.title, br.borrowDate, br.returnDate, br.returned "
              "FROM record br "
              "JOIN user u ON br.userId = u.id "
              "JOIN book b ON br.bookId = b.id "
              "ORDER BY br.borrowDate DESC";
    } else {
        // 普通用户查看自己的记录
        sql = "SELECT br.id, br.bookId, b.title, br.borrowDate, br.returnDate, br.returned "
              "FROM record br "
              "JOIN book b ON br.bookId = b.id "
              "WHERE br.userId = ? "
              "ORDER BY br.borrowDate DESC";
    }

    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    if (currentUser->power != USER_ROOT) {
        sqlite3_bind_int(stmt, 1, currentUser->id);
    }

    int count = 0;
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        printf("记录ID: %d\n", ++count);
        if (currentUser->power == USER_ROOT) {
            printf("用户ID: %d\n", sqlite3_column_int(stmt, 1));
            printf("用户名: %s\n", sqlite3_column_text(stmt, 2));
            printf("图书ID: %d\n", sqlite3_column_int(stmt, 3));
            printf("图书: %s\n", sqlite3_column_text(stmt, 4));
            printf("借阅日期: %s", ctime((time_t*)sqlite3_column_int64(stmt, 5)));
            printf("应还日期: %s", ctime((time_t*)sqlite3_column_int64(stmt, 6)));
        } else {
            printf("图书ID: %d\n", sqlite3_column_int(stmt, 1));
            printf("图书: %s\n", sqlite3_column_text(stmt, 2));
            printf("借阅日期: %s", ctime((time_t*)sqlite3_column_int64(stmt, 3)));
            printf("应还日期: %s", ctime((time_t*)sqlite3_column_int64(stmt, 4)));
        }
        printf("状态: %s\n", sqlite3_column_int(stmt, currentUser->power == USER_ROOT ? 7 : 5) ? "已归还" : "未归还");
        printf("----------------------------\n");
    }
    sqlite3_finalize(stmt);

    if (count == 0) {
        printf("没有借阅记录!\n");
    }
}

//书籍借阅菜单&查照书籍
//PS：若找到，进入借阅函数
void BookBorrow(const char*username)
{
    char bookname[32],info[32];
    char *select = "select * from book where %s = '%s'";
    char sql[LEN];
    while(1)
    {
        memset(sql,0,sizeof(sql));
        memset(info,0,sizeof(info));
        printf("\n======查找书籍======\n");
        printf("(1)按照书名查询\n");
        printf("(2)按照作者查询\n");
        printf("(3)按照类型查询\n");
        printf("(4)返回\n");
        int menu,res,flag=0,num;
        sqlite3_stmt * stmt;
        scanf("%d",&menu);
        switch (menu)
        {
        case 1:
            printf("请输入书名：");
            scanf("%s",info);
            snprintf(sql,sizeof(sql),select,"bookname",info);
            
            res=sqlite3_prepare_v2(db,sql,-1,&stmt,NULL);
            if(res!=SQLITE_OK)
            {
                sqlite3_finalize(stmt);
                printf("查询错误!\n");
                return ;
            }
            printf("\nid     bookname       author         publisher           category       years     num     price\n");
            if(sqlite3_step(stmt)==SQLITE_ROW)
            {
                printf("%-7d%-15s%-15s%-20s%-15s%-10d%-8d%d\n",
                sqlite3_column_int(stmt,0),
                sqlite3_column_text(stmt,1),
                sqlite3_column_text(stmt,2),
                sqlite3_column_text(stmt,3),
                sqlite3_column_text(stmt,4),
                sqlite3_column_int(stmt,5),
                sqlite3_column_int(stmt,6),
                sqlite3_column_int(stmt,7));

                strcpy(bookname,sqlite3_column_text(stmt,1));
                num=sqlite3_column_int(stmt,6);
                flag=1;
            }
            else printf("暂无此书！\n");
            sqlite3_finalize(stmt);
            if(flag)
            {
                res=BorrowRecord(username,bookname,num);
                if(res==1)
                {
                      
                    printf("借阅成功,请在30天内归还!\n");
                    return;
                }
                else if (res==-1) printf("借阅失败！\n");
            }
            break;
        case 2:
            printf("请输入作者：");
            scanf("%s",info);
            snprintf(sql,sizeof(sql),select,"author",info);
            
            res=sqlite3_prepare_v2(db,sql,-1,&stmt,NULL);
            if(res!=SQLITE_OK)
            {
                sqlite3_finalize(stmt);
                printf("查询错误!\n");
                return ;
            }
            printf("\nid     bookname       author         publisher           category       years     num     price\n");
            if(sqlite3_step(stmt)==SQLITE_ROW)
            {
                printf("%-7d%-15s%-15s%-20s%-15s%-10d%-8d%d\n",
                sqlite3_column_int(stmt,0),
                sqlite3_column_text(stmt,1),
                sqlite3_column_text(stmt,2),
                sqlite3_column_text(stmt,3),
                sqlite3_column_text(stmt,4),
                sqlite3_column_int(stmt,5),
                sqlite3_column_int(stmt,6),
                sqlite3_column_int(stmt,7));

                strcpy(bookname,sqlite3_column_text(stmt,1));
                num=sqlite3_column_int(stmt,6);
                flag=1;
            }
            else printf("暂无此书！\n");

            sqlite3_finalize(stmt);
            if(flag)
            {
                res=BorrowRecord(username,bookname,num);
                if(res==1)
                {
                    printf("借阅成功,请在30天内归还!\n");
                    return;
                }
                else if (res==-1) printf("借阅失败！\n");
            }
            break;
        case 3:
            printf("请输入类型：");
            scanf("%s",info);
            snprintf(sql,sizeof(sql),select,"category",info);
            
            res=sqlite3_prepare_v2(db,sql,-1,&stmt,NULL);
            if(res!=SQLITE_OK)
            {
                sqlite3_finalize(stmt);
                printf("查询错误!\n");
                return ;
            }
            printf("\nid     bookname       author         publisher           category       years     num     price\n");
            if(sqlite3_step(stmt)==SQLITE_ROW)
            {
                printf("%-7d%-15s%-15s%-20s%-15s%-10d%-8d%d\n",
                sqlite3_column_int(stmt,0),
                sqlite3_column_text(stmt,1),
                sqlite3_column_text(stmt,2),
                sqlite3_column_text(stmt,3),
                sqlite3_column_text(stmt,4),
                sqlite3_column_int(stmt,5),
                sqlite3_column_int(stmt,6),
                sqlite3_column_int(stmt,7));

                strcpy(bookname,sqlite3_column_text(stmt,1));
                num=sqlite3_column_int(stmt,6);
                flag=1;
            }
            else printf("暂无此书！\n");
            sqlite3_finalize(stmt);
            if(flag)
            {
                res=BorrowRecord(username,bookname,num);
                if(res==1)
                {
                    printf("借阅成功,请在30天内归还!\n");
                    return;
                }
                else if (res==-1) printf("借阅失败！\n");
            }
            break;
        case 4:
            return;
        default:
            printf("请正确选择！\n");
            break;
        }
    }
}


int BorrowRecord(const char *username,const char *bookname,int num)
{
    char sql[LEN];
    int weather;
    while(1)
    {
        
        printf("是否查看评论?\n");
        printf("(1)是\n");
        printf("(2)否\n");
        scanf("%d",&weather);
        clearInputBuffer();
        if(weather==1)
        {viewBookReviews(bookname);}

        else if(weather==2) ;
        else {printf("请正确选择！\n");
        continue;}
        printf("\n是否选择借阅？\n");
        printf("(1)是\n");
        printf("(2)否\n");
        scanf("%d",&weather);
        if(weather==1)
        {
            if(num<=0)
            {
                printf("不可借阅！余量不足！\n");
                return 0;
            }
            num--;

            snprintf(sql,sizeof(sql),"insert into record (username,bookname)values('%s','%s');",username,bookname);
            
            int res = sqlite3_exec(db,sql,NULL,0,NULL);
            if(res!=SQLITE_OK)
            {
                return -1;
            }

            memset(sql,0,sizeof(sql));
            snprintf(sql,sizeof(sql),"update book set num = %d where bookname = '%s';",num,bookname);
            res = sqlite3_exec(db,sql,NULL,0,NULL);
            if(res!=SQLITE_OK)
            {
                return -1;
            }

            return 1;
        }
        else if(weather==2) return 0;
        else printf("请正确选择！\n");
    }
}




void BookReturn(const char* username)
{
    char bookname[32],sql[LEN];
    printf("请输入归还的书籍名称:");
    scanf("%s",bookname);

    while(1)
    {
        sqlite3_stmt *stmt;

        snprintf(sql,sizeof(sql),"select * from record where username = '%s' and bookname = '%s';",username,bookname);
        int res=sqlite3_prepare_v2(db,sql,-1,&stmt,NULL);
        if(res!=SQLITE_OK)
        {
            sqlite3_finalize(stmt);
            printf("查询错误!\n");
            return ;
        }
        int count=0;
        printf("id        username            bookname            borrow_date              return_date\n");
        while(sqlite3_step(stmt)==SQLITE_ROW)
        {
            printf("%-10d%-20s%-20s%-25s%s\n",
            sqlite3_column_int(stmt,0),
            sqlite3_column_text(stmt,1),
            sqlite3_column_text(stmt,2),
            sqlite3_column_text(stmt,3),
            (strcmp(sqlite3_column_text(stmt,4),"0")==1)?"未归还":(char*)sqlite3_column_text(stmt,4));
    
            count++;
        }

        sqlite3_finalize(stmt);
        if(count==0)
        {
            printf("暂无此书借阅记录！\n");
            return;
        }

        printf("请选择要归还的书的记录id(返回输入0):");
        
        int choice;
        scanf("%d",&choice);
        if(choice==0)
        {
            return;
        }

        memset(sql,0,sizeof(sql));
        int result = 0;
        snprintf(sql,sizeof(sql),"select * from record where id = %d;",choice);
        sqlite3_exec(db,sql,ReturnCallBack,&result,NULL);
        if(result==0)
        {
            printf("无此条记录id！请正确输入！\n");
            continue;
        }
        else if(result==1)
        {
            res=AddReturnRecord(choice,bookname);
            if(res==1)
            {
                break;
            }
            else continue;
        }
    }
    return ;
}


//更新book表及record表中的信息
//更新成功返回1，失败返回0
int AddReturnRecord(int choice,const char *bookname)
{
    char sql_1[LEN],sql_2[LEN],sql_3[LEN],sql_4[LEN];
    
    //找出书籍对应的数量及价格，并用num,price储存，同时num自加1
    int num=0,price;
    sqlite3_stmt * stmt_1,*stmt_2,*stmt_3;
    snprintf(sql_1,sizeof(sql_1),"select num,price from book where bookname = '%s';",bookname);
    int res=sqlite3_prepare_v2(db,sql_1,-1,&stmt_1,NULL);
    if(res!=SQLITE_OK)
    {
        printf("归还失败！\n");
        return 0;
    }
    if(sqlite3_step(stmt_1)==SQLITE_ROW)
    {
        num=sqlite3_column_int(stmt_1,0);
        num++;
        price=sqlite3_column_int(stmt_1,1);
        sqlite3_finalize(stmt_1);
    }
    else 
    {
        printf("归还失败！\n");
        return 0;
    }

    //查看记录中是否有归还日期
    char time[32];
    snprintf(sql_2,sizeof(sql_2),"select return_date from record where id = %d;",choice);
    res=sqlite3_prepare_v2(db,sql_2,-1,&stmt_2,NULL);
    if(res!=SQLITE_OK)
    {
        printf("归还失败！\n");
        return 0;
    }
    if(sqlite3_step(stmt_2)==SQLITE_ROW)
    {
        strcpy(time,sqlite3_column_text(stmt_2,0));
        sqlite3_finalize(stmt_2);
        if(strcmp(time,"0")!=0)
        {
            printf("该书已经归还！\n");
            return 0;
        }
    }
    else 
    {
        printf("归还失败！\n");
        return 0;
    }

    //更新记录及书籍数量
    snprintf(sql_3,sizeof(sql_3),"update record set return_date = CURRENT_TIMESTAMP where id = %d;"
                                 "update book set num = %d where bookname = '%s';",choice,num,bookname);
    res=sqlite3_exec(db,sql_3,NULL,0,NULL);
    if(res!=SQLITE_OK)
    {
        printf("归还失败！\n");
        return 0;
    }

    //查看是否超出借阅期限
    char start_time[32],end_time[32];
    snprintf(sql_4,sizeof(sql_4),"select borrow_date,return_date from record where id = %d;",choice);
    res=sqlite3_prepare_v2(db,sql_4,-1,&stmt_3,NULL);
    if(res!=SQLITE_OK)
    {
        printf("归还失败！\n");
        return 0;
    }
    if(sqlite3_step(stmt_3)==SQLITE_ROW)
    {
        strcpy(start_time,sqlite3_column_text(stmt_3,0));
        strcpy(end_time,sqlite3_column_text(stmt_3,1));
    }
    else
    {
        printf("归还失败！\n");
        return 0;
    }
    long diff=manual_time_diff(start_time,end_time);
    if((double)diff / 86400>30)
    //测试时，期限时间设置为5秒，使用下面这个if判断，同时将上面的if判断注释掉
    //if(diff>5)
    {
        printf("逾期归还！请缴纳%d元逾期费!\n",price);
        return 1;
    }

    printf("归还成功！按时归还.\n");
    return 1;
}



//调出借阅历史
void RecordHistory(const char *username)
{
    sqlite3_stmt *stmt;
    char sql[LEN];

    snprintf(sql,sizeof(sql),"select * from record where username = '%s';",username);
    int res=sqlite3_prepare_v2(db,sql,-1,&stmt,NULL);
    if(res!=SQLITE_OK)
    {
        sqlite3_finalize(stmt);
        printf("查询错误!\n");
        return ;
    }
    int count=0;
    while(sqlite3_step(stmt)==SQLITE_ROW)
    {
        printf("username            bookname            borrow_date              return_date\n");
        printf("%-20s%-20s%-25s%s\n",
        sqlite3_column_text(stmt,1),
        sqlite3_column_text(stmt,2),
        sqlite3_column_text(stmt,3),
        sqlite3_column_text(stmt,4));

        count++;
    }

    if(count==0)
    {
        printf("暂无历史记录！\n");
    }
    else printf("查询完毕，共%d次借阅记录。\n",count);

    sqlite3_finalize(stmt);
    return ;
}